package com.chenyuxin.ilp.security.auth.password;


import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class PasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public PasswordAuthenticationFilter(AntPathRequestMatcher pathRequestMatcher,
                                        AuthenticationManager authenticationManager,
                                        AuthenticationSuccessHandler authenticationSuccessHandler,
                                        AuthenticationFailureHandler authenticationFailureHandler){
        super(pathRequestMatcher);
        setAuthenticationManager(authenticationManager);
        setAuthenticationSuccessHandler(authenticationSuccessHandler);
        setAuthenticationFailureHandler(authenticationFailureHandler);
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        log.info("执行用户名密码校验拦截器");
        String requestJsonData = request.getReader()
                .lines().collect(Collectors.joining(System.lineSeparator()));
        Map bean = JSONUtil.toBean(requestJsonData, Map.class);
        String username = (String)bean.get("username");
        String captchaKey = (String)bean.get("captchaKey");
        String captcha = (String)bean.get("captcha");
        String password = (String)bean.get("password");
        HashMap<String, Object> extraParams = new HashMap<>();
        extraParams.put("captchaKey",captchaKey);
        extraParams.put("captcha",captcha);
        PasswordAuthentication passwordAuthentication = new PasswordAuthentication();
        passwordAuthentication.setUsername(username);
        passwordAuthentication.setExtraParams(extraParams);
        passwordAuthentication.setPassword(password);
        passwordAuthentication.setAuthenticated(false);
        return getAuthenticationManager().authenticate(passwordAuthentication);
    }
}
